package com.iteaj.iot.test.server.dtu;

import com.iteaj.iot.CoreConst;
import com.iteaj.iot.server.dtu.impl.CommonDtuProtocol;
import com.iteaj.iot.server.dtu.impl.CommonDtuServerComponent;
import com.iteaj.iot.test.IotTestHandle;
import com.iteaj.iot.utils.ByteUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

@Component
@ConditionalOnExpression("${iot.test.dtu-start:false} and ${iot.test.server:false}")
public class DtuTestHandle implements IotTestHandle {

    @Autowired(required = false)
    private CommonDtuServerComponent serverComponent;

    @Override
    public void start() throws Exception {
        System.out.println("-------------------------------------- Dtu 通用服务测试 ----------------------------------------------");
        serverComponent.getDeviceManager().forEach(item -> {
            Object deviceSn = item.attr(CoreConst.EQUIP_CODE).get();
            if(deviceSn instanceof String) {
                new CommonDtuProtocol((String) deviceSn).writeOfAsync("doing dtu write test".getBytes(StandardCharsets.UTF_8));

                // 等待10秒
                byte[] read = new CommonDtuProtocol((String) deviceSn).timeout(10000).read("read test of waiting 10s".getBytes(StandardCharsets.UTF_8));
                System.out.println(ByteUtil.bytesToHexByFormat(read));
            }
        });
    }

    @Override
    public int getOrder() {
        return 5000;
    }
}
